<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/4
 * Time: 14:07
 * 服务器组的操作
 */
class Servergroup_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * @param $data
     * @return bool
     * 添加服务器组
     */
    public function add($data)
    {
        $result = $this->db->insert('name_servers_groups',$data);
        return $result;
    }

    /**
     * @param $page
     * @param $pagesize
     * @return array
     * 分页显示列表
     */
    public function getGroupList($page,$pagesize)
    {
        $rows = $this->db->select()->from('name_servers_groups')
                    ->limit($pagesize,($page-1)*$pagesize)
                    ->get()
                    ->result_array();
        $num = $this->db->select()->from('name_servers_groups')
            ->get()
            ->num_rows();
        $data = array(
            'group'=> $rows,
            'num' => $num
        );
        return $data;
    }

    /**
     * @param int $id
     * @return mixed
     * 获取单条数据
     */
    public function getIdData($id)
    {
        $rows = $this->db->select()->from('name_servers_groups')
                        ->where('id',$id)
                        ->get()
                        ->result_array();
        if(!empty($rows))
        {
            return $rows[0];
        }
        return false;
    }

    /**
     * @param $data
     * @return bool
     * 修改数据
     */
    public function update($data)
    {
        $result = $this->db->replace('name_servers_groups',$data);
        return $result;
    }
    /**
     * @param $id
     * @return bool
     * 根据id删除数据
     */
    public function del($id)
    {
        //查看该组下面是否有组员如果有组员表示不能删除
        $rows = $this->db->select()->from('dns_domains_groups')
                ->where('id_group',$id)
                ->get()
                ->result_array();

        if(!empty($rows))
        {
            $code = '2';//表示含有组员不能删除
        }else
        {
            $result = $this->db->delete('name_servers_groups',array('id'=>$id));
            if($result === true)
            {
                $code = '1';
            }else
            {
                $code = '0';
            }
        }
        return $code;
    }
    public function getGroupMember()
    {
        $rows = $this->db->select()->from('name_servers')
            ->get()
            ->result_array();
        $groupMember = array();
        $data = array();
        if($rows)
        {
            foreach($rows as $row)
            {
                if($row['server_name'])
                {
                    $groupMember[$row['id_group']][] =$row['server_name'];
                }

            }

            foreach($groupMember as $k =>$val)
            {
                $data[$k] = implode(',',$groupMember[$k]);
            }
        }
        return $data;
    }
}